package network2023;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/4/24 22:00
 * 回显程序的客户端
 */
public class UdpEchoClient {

    private DatagramSocket socket = null;
    private String serverIP; // 服务器 IP
    private int serverPort; // 服务端口

    // 客户端启动需要知道服务器ip和端口
    public UdpEchoClient(String serverIP, int serverPort) throws SocketException {
        socket = new DatagramSocket(); // 系统自动分配空闲端口
        this.serverIP = serverIP;
        this.serverPort = serverPort;
    }

    // 启动客户端
    public void start() throws IOException {
        // 通过客户端可以和服务器多次交互
        Scanner scan = new Scanner(System.in);
        while (true) {
            // 1. 先从控制台读取一个字符串
            System.out.print("->");
            String request = scan.next();
            // 2. 把字符串构造成 UDP packet 进行发送
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(serverIP), serverPort);
            socket.send(requestPacket);
            // 3. 客户端尝试读取服务器返回的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            // 4. 响应数据转化成 String 并显示
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.printf("req: %s, resp: %s\n", request, response);
        }
    }


    public static void main(String[] args) throws IOException {
        // localhost -> 127.0.0.1 环回ip -> 客户端和服务端位于同一主机
        UdpEchoClient udpEchoClient = new UdpEchoClient("localhost", 9090);
        udpEchoClient.start();
    }
}
